document.addEventListener('DOMContentLoaded', function() {
    loadUserProfile();
    setupFormListeners();
});

// 加载用户信息
async function loadUserProfile() {
    try {
        const response = await fetch('/api/user/profile');
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '加载用户信息失败');
        }
        const data = await response.json();
        document.getElementById('username').value = data.username;
        document.getElementById('email').value = data.email;
    } catch (error) {
        showMessage(error.message, 'error');
    }
}

// 设置表单提交监听
function setupFormListeners() {
    const profileForm = document.getElementById('profileForm');
    const passwordForm = document.getElementById('passwordForm');

    profileForm.addEventListener('submit', async function(event) {
        event.preventDefault();
        const formData = {
            username: document.getElementById('username').value,
            email: document.getElementById('email').value
        };

        try {
            const response = await fetch('/api/user/profile', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const result = await response.json();
            if (!response.ok) {
                throw new Error(result.error || '更新失败');
            }
            showMessage(result.message, 'success');
            // 更新页面顶部的用户名显示
            const userDisplay = document.querySelector('header button');
            if (userDisplay) {
                userDisplay.textContent = `退出登录 (${formData.username})`;
            }
        } catch (error) {
            showMessage(error.message, 'error');
        }
    });

    passwordForm.addEventListener('submit', async function(event) {
        event.preventDefault();
        const formData = {
            current_password: document.getElementById('current_password').value,
            new_password: document.getElementById('new_password').value,
            confirm_password: document.getElementById('confirm_password').value
        };

        try {
            const response = await fetch('/api/user/password', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const result = await response.json();
            if (!response.ok) {
                throw new Error(result.error || '密码修改失败');
            }
            showMessage(result.message, 'success');
            passwordForm.reset(); // 清空密码字段
        } catch (error) {
            showMessage(error.message, 'error');
        }
    });
}

// 显示消息提示
function showMessage(message, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.textContent = message;
    document.body.appendChild(messageDiv);

    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 3000);
}
